package kokonut.shop.cart;

import java.io.Serializable;
import java.util.ArrayList;

import kokonut.shop.color.ExistingColors;
import kokonut.shop.product.TShirt;
import kokonut.shop.size.ExistingSizes;

public class CartController implements Serializable{

	private Cart cart = Cart.getInstance();

	public void addProductToCart(TShirt shirt)
	{
		this.cart.addProduct(shirt);
	}

	public void addProductToCart(TShirt shirt, int amount)
	{
		this.cart.addProduct(shirt,amount);
	}

	public ArrayList<SelectedProduct> loadProductsInCart()
	{
		return cart.getProductList();
	}

	public float getTotalPrice()
	{
		return cart.getTotal();
	}

	public boolean productAlreadyInCart(TShirt shirt)
	{
		ArrayList<SelectedProduct> productList = cart.getProductList();
		if(productList != null)
			for(SelectedProduct product:productList)
				if(product.getProduct().getColor() == shirt.getColor() &&
				   product.getProduct().getRef() == shirt.getRef() &&
				   product.getProduct().getSize() == shirt.getSize())
					return true;
		return false;
	}

	public void updateProductInCart(TShirt shirt, int amount) {
		ArrayList<SelectedProduct> productList = cart.getProductList();
		for(int i = 0; i < productList.size(); i++)
		{
			SelectedProduct product = productList.get(i);
			if(product.getProduct().getColor() == shirt.getColor() &&
			   product.getProduct().getRef() == shirt.getRef() &&
			   product.getProduct().getSize() == shirt.getSize())
			{
				product.setAmount(product.getAmount() + amount);
				cart.getProductList().set(i, product);
			}
		}
	}

	public void deleteFromCart(int ref, ExistingColors color, ExistingSizes size)
	{
		ArrayList<SelectedProduct> productList = cart.getProductList();
		for(int i = 0; i < productList.size(); i++)
		{
			SelectedProduct product = productList.get(i);
			if(product.getProduct().getColor() == color &&
			   product.getProduct().getRef() == ref &&
			   product.getProduct().getSize() == size)
			{
				cart.getProductList().remove(i);
			}
		}
	}

	/**
	 * Resturns the product in the specified position of the cart
	 * @param position: the position of the product we want to get
	 * @return SelectedProduct object with choosed product
	 */
	public SelectedProduct getProductByPosition(int position)
	{
		return cart.getProductList().get(position);
	}

	/**
	 * Returns the number of products added to the cart
	 * @return
	 */
	public int getNumberOfProducts()
	{
		if (cart.getProductList()!=null)
		{
			int numberOfProducts = 0;
			for(SelectedProduct product: cart.getProductList())
				numberOfProducts += product.getAmount();
			return numberOfProducts;
		}
		return 0;
	}
}